﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Mad.Nug.Rss;

namespace Mad.Nug
{
    public partial class ViewItem : PhoneApplicationPage
    {
        public ViewItem()
        {
            InitializeComponent();
            this.DataContext = (App.Current as App).selectedItem;

            RssReader commentsReader = new RssReader();
            commentsReader.rssSource = (App.Current as App).selectedItem.CommentsUrl.ToString();
            commentsReader.LoadRssItems();
            lstComments.DataContext = commentsReader;
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
            {
                if (App.HaveConnection())
                {
                    browser.LoadCompleted += new System.Windows.Navigation.LoadCompletedEventHandler(browser_LoadCompleted);
                    browser.NavigateToString((App.Current as App).selectedItem.Description);
                }
                else
                {
                    MessageBox.Show("No dispone de una conexión de datos en estos momentos.");
                }
            }
        }

        void browser_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            browser.LoadCompleted -= browser_LoadCompleted;
            pbarloading.Visibility = System.Windows.Visibility.Collapsed;
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            EnterPage.Begin();
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true;
            ExitPage.Completed += new EventHandler(ExitPage_Completed);
            ExitPage.Begin();
        }

        void ExitPage_Completed(object sender, EventArgs e)
        {
            ExitPage.Completed -= ExitPage_Completed;
            this.NavigationService.GoBack();
        }

        private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
        {
            RssItem Context = (RssItem)this.DataContext;
            Microsoft.Phone.Tasks.WebBrowserTask navegador = new Microsoft.Phone.Tasks.WebBrowserTask();
            navegador.URL = Context.Url.OriginalString;
            navegador.Show();
        }
    }
}
